<?php
/**
 * SendMail.php
 * User: wuchunhe
 * Date: 2021/5/27 2:13 下午
 */

//邮件发送
namespace sendcloud;

use sendcloud\lib\util\HttpClient;
use sendcloud\lib\SendCloud;
use sendcloud\lib\util\Attachment;
use sendcloud\lib\util\Mail;
use sendcloud\lib\util\TemplateContent;
use sendcloud\lib\util\Mimetypes;

class SendMail
{
    protected $sendcloud;
    protected $email;

    public function __construct()
    {
        $this->sendcloud = new SendCloud();
        $this->email = new Mail();
    }

    /**
     * 设置邮件内容
     * @param $subject
     * @param $from
     * @param $sendTo
     * @param $content
     * @param $name
     * @param null $cc
     * @return $this
     * author: wuchunhe
     * Date: 2021/6/3 3:53 下午
     */
    public function setEmailAttributes($subject, $from, $sendTo, $content, $name = '', $cc = null)
    {
        $this->email->setSubject($subject);
        $this->email->setFrom($from ?? env('SEND_FROM'));
        $this->email->addTo($sendTo);
        $cc && $this->email->addCc($cc);
        $this->email->setReplyTo($from);
        $this->email->setFromName($name.env('SENDER_NAME'));
        $this->email->setContent($content);
        $this->email->setRespEmailId(true);
    }

    /**
     * 设置邮件附件
     * @param array $attachs
     * @return $this
     * author: wuchunhe
     * Date: 2021/6/3 1:48 下午
     */
    public function setAttach(array $attachs)
    {
        //循环写入文件资源
        foreach ($attachs as $key => $val) {
            //截取文件名称
            $filePath = trim(urldecode($val), '"');
            $name = substr($filePath, strrpos($filePath, '/') + 11);
            //附件路径
            $file = storage_path('app/public') . '/' . $filePath;
            $handle = fopen($file, 'rb');
            $content = fread($handle, filesize($file));
            $filetype = Mimetypes::getInstance()->fromFilename($file);

            $attachment = new Attachment();
            $attachment->setType($filetype);
            $attachment->setContent($content);
            $attachment->setFilename($name);
            $this->email->addAttachment($attachment);
            fclose($handle);
        }
    }

    /**
     * @return array
     * author: wuchunhe
     * Date: 2021/6/3 3:47 下午
     */
    public function send()
    {
        return $this->sendcloud->sendCommon($this->email);
    }

}